<template>
  <div class="container">
    <div class="item">
      发布时间&nbsp;&nbsp;
      <el-date-picker
        v-model="searchForm.onlineTime"
        placeholder="发布时间"
        value-format="yyyy-MM-dd HH:mm"
        class="search-item date-range-item"
        type="datetime"
      />
    </div>
    <div class="item">
      &nbsp;&nbsp;来源应用服务
      <el-select v-model="application" placeholder="全部">
        <el-option label="ebroker" value="00" />
        <el-option label="车E家" value="01" />
      </el-select>
    </div>
    <div class="item">
      版&nbsp;本&nbsp;号&nbsp;&nbsp;&nbsp;&nbsp;
      <el-input
        v-model="searchForm.version"
        placeholder="请输入版本号如：1.0.0"
        style="width: 300px"
      />
      <br>
      <span
        style="margin-left: 80px; color: #ccc; display: block; margin-top: 10px"
      >
        注意：版本号不可低于当前版本</span>
    </div>
    <div class="item" style="display: flex">
      <span> 安装包</span>
      <ul style="margin-left: 30px">
        <input
          id="iosChecked"
          v-model="iosChecked"
          type="checkbox"
          value="0"
        >&nbsp;&nbsp;IOS&nbsp; &nbsp;&nbsp;
        <el-input
          v-model="searchForm.iosFileUrl"
          placeholder="请输入App Store应用页面地址"
          style="width: 300px"
        />
        <br>
        <div class="myItem" style="margin-top: 15px">
          版本说明
          <textarea
            id="iosRemark"
            v-model="searchForm.iosRemark"
            maxlength="200"
            rows="6"
            cols="35"
            style="vertical-align: top; padding: 10px"
            placeholder="请输入版本更新说明，不超过200字"
          />
        </div>
      </ul>
    </div>
    <div class="item" style="display: flex">
      <span style="width: 50px" />

      <ul style="margin-left: 30px">
        <input
          id="androidChecked"
          v-model="androidChecked"
          type="checkbox"
          value="1"
        >&nbsp;&nbsp;Android&nbsp;
        <el-input
          v-model="name"
          placeholder="请上传APK文件"
          style="width: 300px"
        />
        <!-- <input id="upload_file" ref="upload_file" type="file" style="display: none;" accept=".apk"> -->
        <el-button type="primary" @click="upload">上传</el-button>
        <!-- <a href="#" class="easyui-linkbutton" onclick="upload_file.click();" style="transform: translateY(-5px);">上传</a> -->
        <br>
        <div class="myItem" style="margin-top: 15px">
          版本说明
          <textarea
            id="androidRemark"
            v-model="searchForm.androidRemark"
            maxlength="200"
            rows="6"
            cols="35"
            style="vertical-align: top; margin-left: 10px; padding: 10px"
            placeholder="请输入版本更新说明，不超过200字"
          />
        </div>
      </ul>
    </div>
    <div class="item" style="display: flex">
      强制更新
      <ul style="margin-left: 30px">
        <input
          v-model="searchForm.isForceUpdate"
          type="radio"
          class="yes"
          name="question1"
          value="1"
        >
        是
        <input
          v-model="searchForm.isForceUpdate"
          type="radio"
          class="no"
          style="margin-left: 50px"
          name="question1"
          value="0"
        >
        否
      </ul>
    </div>

    <div class="item" style="width: 450px; text-align: right">
      <el-button type="primary" @click="add">{{
        id == 0 ? "提交发布" : "编辑发布"
      }}</el-button>
    </div>
  </div>
</template>

<script>
const OSS = require('ali-oss')

console.log(process.env)
export default {
  name: 'AddVersion',
  data() {
    return {
      name: '',
      file: null,
      id: 0,
      androidChecked: false,
      iosChecked: false,
      application: '',
      searchForm: {
        androidFileUrl: '',
        androidRemark: '',
        iosFileUrl: '',
        iosRemark: '',
        isForceUpdate: '',
        onlineTime: '',
        platform: '',
        version: ''
      },
      client: null
    }
  },
  created() {
    this.id = Number(this.$route.query.id) || 0
    if (!this.$route.query.id) return
    this.$get('web/appVersion/get', { id: this.$route.query.id }).then(
      (res) => {
        if (res.data.code === '0') {
          this.searchForm.onlineTime = res.data.data.onlineTime
          this.searchForm.isForceUpdate = res.data.data.isForceUpdate
          this.searchForm.platform = res.data.data.platform
          this.application = res.data.data.application
          if (this.searchForm.platform === 1) {
            this.searchForm.androidFileUrl = res.data.data.fileUrl
            this.name = this.searchForm.androidFileUrl.substring(this.searchForm.androidFileUrl.lastIndexOf('/') + 1)

            this.searchForm.androidRemark = res.data.data.remark
            this.androidChecked = true
          } else {
            this.searchForm.iosFileUrl = res.data.data.fileUrl
            this.searchForm.iosRemark = res.data.data.remark
            this.iosChecked = true
          }

          this.searchForm.version = res.data.data.version
        }
      }
    )
  },
  mounted() {
    this.$post('/app/upload/getOssStsTokenInfo', {}, 'json').then(res => {
      this.client = new OSS({
        // yourRegion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
        region: 'oss-cn-shenzhen',
        // 从STS服务获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
        accessKeyId: res.data.data.accessKeyId,
        accessKeySecret: res.data.data.accessKeySecret,
        // 从STS服务获取的安全令牌（SecurityToken）。
        stsToken: res.data.data.securityToken,
        timeout: 5 * 60 * 1000,
        // 填写Bucket名称。
        bucket: process.env.NODE_ENV === 'test' ? 'ecar-test' : 'ecar-broker'
      })
    })
  },
  methods: {
    upload() {
      const input = document.createElement('input')
      input.accept = '.apk'
      input.type = 'file'
      input.style.display = 'none'
      input.onchange = async() => {
        console.log(input.files)
        this.name = input.files[0].name
        console.log(this.name)
        const Form = new FormData()
        Form.append('file', input.files[0])
        const loading = this.$loading({
          lock: true,
          text: '文件上传中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        const result = await this.client.put(`/ecar/web/appVersion/${this.name}.apk`, input.files[0])
        try {
          // console.log(result)
          loading.close()
          this.searchForm.androidFileUrl = result.url
        } catch (error) {
          loading.close()
        }
        // this.$upload('/web/upload/bigFile?source=web&type=appVersion', Form).then(
        //   (res) => {
        //     loading.close()
        //     if (res.data.code === '0') {
        //       this.searchForm.androidFileUrl = res.data.data
        //       this.$message.success('文件上传成功')
        //     } else {
        //       this.$message.error('文件上传失败')
        //     }
        //   }
        // ).catch(() => {
        //   loading.close()
        // })

        // this.file = input.files

        // setTimeout(() => {}, 10000)
      }
      input.click()
    },
    add() {
      if (new Date(this.searchForm.onlineTime).getTime() - Date.now() < 0) {
        this.$message.error('发布时间不能大于当前时间')
        return
      }
      if (this.searchForm.version === '') {
        this.$message.error('请输入版本号')
        return
      }
      if (!this.androidChecked && !this.iosChecked) {
        this.$message.error('请选择平台')
        return
      }
      if (this.androidChecked) {
        this.searchForm.platform = 1
        if (this.searchForm.androidFileUrl === '') {
          this.$message.error('请上传Android的APK文件')
          return
        }
        if (this.searchForm.androidRemark === '') {
          this.$message.error('版本说明不能为空')
          return
        }
      } else if (this.iosChecked) {
        this.searchForm.platform = 2
        if (this.searchForm.iosFileUrl === '') {
          this.$message.error('IOS地址不能为空')
          return
        }
        if (this.searchForm.iosRemark === '') {
          this.$message.error('版本说明不能为空')
          return
        }
      }
      if (this.androidChecked && this.iosChecked) {
        this.searchForm.platform = 3
      }
      if (this.id === 0) {
        this.$post(
          'web/appVersion',
          {
            ...this.searchForm,
            id: this.id,
            application: this.application
          },
          'json'
        ).then((res) => {
          if (res.data.code === '0') {
            this.$message.success('新增成功')
            this.$router.back()
          }
        })
      } else {
        this.$put(
          'web/appVersion',
          {
            ...this.searchForm,
            id: this.id,
            application: this.application
          },
          'json'
        ).then((res) => {
          if (res.data.code === '0') {
            this.$message.success('编辑成功')
            this.$router.back()
          }
        })
      }
    }
  }
}
</script>

<style>
.container {
  margin: 0 30px;
}

.container .item {
  margin-top: 30px;
}
.easyui-linkbutton {
  margin-top: 15px;
}
textarea {
  border: 1px solid #dcdfe6;
  font-size: 15px;
}
</style>
